<template>
  <el-card shadow="never" class="box-card" style="margin-top: 10px">
    <el-card shadow="never" class="box-card" style="margin-top: 10px">
      <div>
        <FormRender ref="formRenderRef" @form-change="onFormChange()" />
      </div>
    </el-card>
    <div>
      <el-card shadow="never" class="box-card" style="margin-top: 10px">
        <template #header> 发起人 </template>

        <SelectorUser
          :multiple="false"
          :inline="true"
          :user-selector="userSelector"
          :users="users"
          :index="index"
          v-for="(userSelector, index) in userSelectors"
          :key="index"
          @change="onNodeUserChange"
        />
      </el-card>

      <div style="text-align: right">
        <el-checkbox v-model="isSimulation">是否模拟</el-checkbox>
        <br />
        <el-button type="primary" @click="onSubmit">提 交</el-button>
      </div>
    </div>
    <br />
    <el-card shadow="never" class="box-card" style="margin-top: 10px">
      <template #header>
        <div class="card-header">
          <span
            >审批用户（<el-button type="text" size="mini" @click="refreshUser"
              >刷新</el-button
            >）</span
          >
        </div>
        <el-text class="mx-1" size="large">（点击按钮切换当前用户）</el-text>
      </template>
      <div>
        <ForecastHandleUser ref="forecastHandleUserRef" :task-id="worktaskId" />
      </div>
    </el-card>
  </el-card>
</template>

<script setup>
import { reactive, ref, unref, nextTick, watch } from "vue";
import { useWorkTaskStore } from "@/stores/workTask";
import { useDynamicFormDesignStore } from "@/stores/dynamicFormDesign";
import { useOrganisationUserStore } from "@/stores/organisationUser";
import ForecastHandleUser from "./ForecastHandleUser.vue";
import { useAppUserStore } from "@/stores/appUser";
import SelectorUser from "./../FlowProcesses/SelectorUser.vue";
import FormRender from "@/components/WorkflowDesign/formComponents/FormRender.vue";

const props = defineProps({
  workflowInfo: {
    default: () => ({
      id: "",
      version: 0,
      formVersion: 0,
    }),
  },
});

const emit = defineEmits(["update:value"], ["workTaskStart"]);

const loading = ref(false);
const formRenderRef = ref(null);
const isSimulation = ref(true);

const workTaskStore = useWorkTaskStore();
const dynamicFormDesignStore = useDynamicFormDesignStore();
const organisationUserStore = useOrganisationUserStore();
const forecastHandleUserRef = ref(null);

const appUserStore = useAppUserStore();

const worktaskId = ref("");
const workflowInfo = ref({
  workflowId: "",
  versionNo: 0,
  formData: "",
});

const userSelectors = ref([{}]);
const users = ref([]);

const load = async () => {
  await nextTick();

  setTimeout(() => {
    formRenderRef.value.setDesignContent("", "");
    formRenderRef.value.setFormData({});
    getFormDesignVersionByWorkflowIdAndVersion();
    onFormChange();
  }, 500);
};

const getFormDesignVersionByWorkflowIdAndVersion = async () => {
  loading.value = true;
  const res = await dynamicFormDesignStore.getFormDesignVersionByWorkflowIdAndVersion({
    formVersion: props.workflowInfo.formVersion,
    workflowId: props.workflowInfo.id,
  });
  if (res) {
    formRenderRef.value.setDesignContent(
      res.designContent,
      res.designFramework
    );
  }
  else{
    formRenderRef.value.setDesignContent(
      "{}",
      ""
    );
  }
  loading.value = false;
};

const onSubmit = async () => {
  emit("workTaskReset");
  formRenderRef.value.validateForm(async (valid) => {
    if (!valid) return;
    loading.value = true;
    const workTaskForm = {
      id: "",
      createdUserId: organisationUserStore.getCurrentUser?.id,
      entityFullName: "Simulation",
      entityKeyValue: new Date().getTime().toString(),
      formData: await formRenderRef.value.getFormData(),
      workTaskStatus: "",
      name: "模拟流程",
      workflowId: {
        versionNo: props.workflowInfo.version,
        id: props.workflowInfo.id,
      },
    };

    let res = await (isSimulation.value
      ? workTaskStore.createSimulationWorkTask(workTaskForm)
      : workTaskStore.createWorkTask(workTaskForm));
    worktaskId.value = res.id;
    const data = {
      workTaskId: res.id,
    };
    await workTaskStore.startWorkTask(data);
    getForecastNodeUsers4Task(res.id);
    loading.value = false;
    emit("workTaskStart", { taskId: res.id });
  });
};

const getForecastNodeUsers4Task = (taskId) => {
  forecastHandleUserRef.value.getForecastNodeUsers4Task(taskId);
};

const onFormChange = async () => {
  formRenderRef.value.validateForm(async (valid) => {
    if (valid) {
      let data = await formRenderRef.value.getFormData();
      workflowInfo.value = {
        workflowId: props.workflowInfo.id,
        versionNo: props.workflowInfo.version,
        formData: data,
      };
      forecastHandleUserRef.value.getForecastNodeUsers4Workflow(
        workflowInfo.value
      );
    }
  });
};
const refreshUser = () => {
  getForecastNodeUsers4Task(worktaskId.value);
};

const onNodeUserChange = (val) => {
  userSelectors.value[val.index] = val.selector;
  users.value = val.users;
  if (val.users.length > 0) {
    const user = val.users[0];
    appUserStore.setCurrentUser({ id: user.id, name: user.name });
  }
};
defineExpose({
  load,
});
</script>

<style lang="less" scoped>
:deep(.no-header-dialog) {
  padding: 0px !important;

  .el-dialog__header {
    padding: 9px;
    height: 30px;
    text-align: right;
  }

  .el-dialog__body {
    width: 100%;
    height: calc(100vh - 150px);
    padding: 0px !important;
  }
}
.content-box {
  padding: 10px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}
</style>
